/**
 * 天空盒UI控制面板
 * 提供完整的天空盒参数调节界面
 */

import { SkyboxPanelUI } from './SkyboxPanelUI.js';
import { SkyboxPanelEvents } from './SkyboxPanelEvents.js';
import * as THREE from '../../lib/three/build/three.module.js';

class SkyboxPanel {
    constructor(skyboxManager) {
        this.skyboxManager = skyboxManager;
        this.panel = null;
        this.events = null;
        this.isVisible = false;
        this.hasUnsavedChanges = false;
        this.savedConfig = null;
        
        // 预设配置
        this.presets = {
            '默认天空': {
                useGradient: true,
                topLine: 0.4,
                skyline: 0.0,
                groundLine: -0.2,
                bottomLine: -0.4,
                topColor: '#1e90ff',        // 道奇蓝 - 深邃的蔚蓝
                middleSkyColor: '#87ceeb',  // 天空蓝 - 清澈明亮
                skylineColor: '#b0e2ff',    // 浅天蓝 - 地平线过渡
                groundColor: '#d4a574',     // 暖沙色 - 自然地面色
                bottomColor: '#8b7355',     // 棕褐色 - 地面阴影
                topColorIntensity: 1.0,
                middleSkyColorIntensity: 1.0,
                skylineColorIntensity: 1.0,
                groundColorIntensity: 0.8,
                bottomColorIntensity: 0.6
            },
            '日出': {
                useGradient: true,
                topLine: 0.35,
                skyline: -0.05,
                groundLine: -0.25,
                bottomLine: -0.45,
                topColor: '#5a9fd4',        // 清晨蓝
                middleSkyColor: '#ffa07a',  // 浅鲑红 - 晨光
                skylineColor: '#ff8c69',    // 橙红 - 日出核心
                groundColor: '#ff6347',     // 番茄红 - 地平线暖光
                bottomColor: '#4a3728',     // 深棕 - 未被照亮的地面
                topColorIntensity: 0.9,
                middleSkyColorIntensity: 1.3,
                skylineColorIntensity: 1.6,
                groundColorIntensity: 1.2,
                bottomColorIntensity: 0.5
            },
            '日落': {
                useGradient: true,
                topLine: 0.3,
                skyline: -0.1,
                groundLine: -0.3,
                bottomLine: -0.5,
                topColor: '#2c4a7c',        // 暮光蓝
                middleSkyColor: '#ff7f50',  // 珊瑚橙
                skylineColor: '#ff6347',    // 番茄红 - 夕阳核心
                groundColor: '#cc4125',     // 深橙红
                bottomColor: '#3d2817',     // 深棕黑
                topColorIntensity: 0.7,
                middleSkyColorIntensity: 1.5,
                skylineColorIntensity: 2.0,
                groundColorIntensity: 1.4,
                bottomColorIntensity: 0.4
            },
            '夜空': {
                useGradient: true,
                topLine: 0.5,
                skyline: 0.1,
                groundLine: -0.15,
                bottomLine: -0.35,
                topColor: '#000428',        // 深夜蓝
                middleSkyColor: '#004e92',  // 午夜蓝
                skylineColor: '#1a3a52',    // 深蓝灰 - 地平线
                groundColor: '#1c1c1c',     // 深灰
                bottomColor: '#0d0d0d',     // 近黑
                topColorIntensity: 0.4,
                middleSkyColorIntensity: 0.6,
                skylineColorIntensity: 0.8,
                groundColorIntensity: 0.3,
                bottomColorIntensity: 0.2
            },
            '阴天': {
                useGradient: true,
                topLine: 0.4,
                skyline: 0.05,
                groundLine: -0.15,
                bottomLine: -0.35,
                topColor: '#6b7c8c',        // 灰蓝 - 云层上方
                middleSkyColor: '#b0bec5',  // 浅灰蓝 - 厚云层
                skylineColor: '#cfd8dc',    // 浅云灰 - 地平线云层
                groundColor: '#9e9e9e',     // 中灰 - 阴影地面
                bottomColor: '#616161',     // 深灰 - 暗部
                topColorIntensity: 0.6,
                middleSkyColorIntensity: 0.8,
                skylineColorIntensity: 1.0,
                groundColorIntensity: 0.7,
                bottomColorIntensity: 0.5
            },
            '晴朗午后': {
                useGradient: true,
                topLine: 0.45,
                skyline: 0.05,
                groundLine: -0.1,
                bottomLine: -0.25,
                topColor: '#0080ff',        // 鲜艳蓝天
                middleSkyColor: '#00bfff',  // 深天蓝
                skylineColor: '#e0f6ff',    // 极浅蓝 - 明亮地平线
                groundColor: '#f5deb3',     // 小麦色 - 阳光照射的地面
                bottomColor: '#daa520',     // 金黄 - 明亮地面
                topColorIntensity: 1.1,
                middleSkyColorIntensity: 1.2,
                skylineColorIntensity: 1.0,
                groundColorIntensity: 0.9,
                bottomColorIntensity: 0.7
            },
            '星空': {
                useGradient: true,
                topLine: 0.6,
                skyline: 0.2,
                groundLine: -0.1,
                bottomLine: -0.3,
                topColor: '#000033',        // 深邃夜空
                middleSkyColor: '#0d1b2a',  // 午夜蓝黑
                skylineColor: '#1b263b',    // 深蓝灰 - 夜空地平线
                groundColor: '#0a0e1a',     // 深灰黑
                bottomColor: '#050505',     // 近黑
                topColorIntensity: 0.3,
                middleSkyColorIntensity: 0.4,
                skylineColorIntensity: 0.6,
                groundColorIntensity: 0.25,
                bottomColorIntensity: 0.15
            }
        };
        
        this.createPanel();
    }
    
    /**
     * 创建面板
     */
    createPanel() {
        // 在左侧面板容器中创建天空盒tab内容
        const scenePanel = document.getElementById('scene-panel');
        if (!scenePanel) {
            console.error('❌ 未找到scene-panel容器');
            return;
        }
        
        const panel = document.createElement('div');
        panel.id = 'skybox-tab';
        panel.className = 'left-tab-content';
        panel.innerHTML = SkyboxPanelUI.generateHTML(this.presets);
        
        // 添加样式
        this.addStyles();
        
        scenePanel.appendChild(panel);
        this.panel = panel;
        
        // 创建事件处理器
        this.events = new SkyboxPanelEvents(panel, this.skyboxManager);
        this.events.bindAll();
        
        // 绑定自定义事件
        this.bindCustomEvents();
        
        // 默认隐藏
        this.hide();
        
        console.log('✅ 天空盒面板创建完成');
    }
    
    /**
     * 添加样式
     */
    addStyles() {
        if (document.getElementById('skybox-panel-styles')) return;
        
        const style = document.createElement('style');
        style.id = 'skybox-panel-styles';
        style.textContent = SkyboxPanelUI.generateCSS();
        
        document.head.appendChild(style);
    }
    
    /**
     * 绑定自定义事件
     */
    bindCustomEvents() {
        // 应用预设
        this.panel.addEventListener('applyPreset', (e) => {
            this.applyPreset(e.detail);
        });
        
        // 重置
        this.panel.addEventListener('reset', () => {
            this.reset();
        });
        
        // 保存按钮
        const saveBtn = this.panel.querySelector('#save-skybox');
        if (saveBtn) {
            saveBtn.addEventListener('click', () => {
                this.saveSkyboxConfig();
            });
        }
        
        // 监听所有参数变化
        this.panel.querySelectorAll('input, select').forEach(input => {
            input.addEventListener('change', () => {
                this.markAsUnsaved();
            });
            input.addEventListener('input', () => {
                this.markAsUnsaved();
            });
        });
    }
    
    /**
     * 显示面板
     */
    show() {
        if (this.panel) {
            this.panel.classList.add('active');
            this.isVisible = true;
        }
    }
    
    /**
     * 隐藏面板
     */
    hide() {
        if (this.panel) {
            this.panel.classList.remove('active');
            this.isVisible = false;
        }
    }
    
    /**
     * 切换显示（由toggleLeftTab统一处理）
     */
    toggle() {
        // 不再需要单独的toggle逻辑，由index.html中的toggleLeftTab处理
        console.log('天空盒tab切换由toggleLeftTab统一管理');
    }
    
    /**
     * 应用预设
     */
    applyPreset(name) {
        const preset = this.presets[name];
        if (!preset) {
            console.warn(`预设 "${name}" 不存在`);
            return;
        }
        
        this.skyboxManager.applyConfig(preset);
        this.events.updateUIFromConfig(preset);
        
        console.log(`✅ 已应用预设: ${name}`);
        
        // 应用预设后立即保存
        this.saveSkyboxConfig();
    }
    
    
    /**
     * 重置为默认配置
     */
    reset() {
        this.applyPreset('默认天空');
    }
    
    /**
     * 标记为未保存
     */
    markAsUnsaved() {
        this.hasUnsavedChanges = true;
        const saveBtn = this.panel.querySelector('#save-skybox');
        if (saveBtn) {
            saveBtn.classList.add('unsaved');
            saveBtn.textContent = '💾 保存 *';
        }
    }
    
    /**
     * 标记为已保存
     */
    markAsSaved() {
        this.hasUnsavedChanges = false;
        const saveBtn = this.panel.querySelector('#save-skybox');
        if (saveBtn) {
            saveBtn.classList.remove('unsaved');
            saveBtn.textContent = '💾 保存';
        }
    }
    
    /**
     * 显示保存状态
     */
    showSaveStatus(message, type = 'success') {
        const statusDiv = this.panel.querySelector('#skybox-save-status');
        if (statusDiv) {
            statusDiv.className = `skybox-save-status ${type}`;
            statusDiv.textContent = message;
            
            // 3秒后自动隐藏
            setTimeout(() => {
                statusDiv.className = 'skybox-save-status';
            }, 3000);
        }
    }
    
    /**
     * 保存天空盒配置到场景
     */
    async saveSkyboxConfig() {
        try {
            console.log('💾 开始保存天空盒配置...');
            
            // 获取当前项目和场景
            const projectManager = window.projectManager;
            if (!projectManager) {
                throw new Error('项目管理器未初始化');
            }
            
            const currentProject = projectManager.getCurrentProject();
            if (!currentProject) {
                throw new Error('当前没有打开的项目');
            }
            
            const sceneId = projectManager.getDefaultSceneId();
            if (!sceneId) {
                throw new Error('未找到默认场景');
            }
            
            // 获取当前配置
            const config = this.skyboxManager.getConfig();
            console.log('当前天空盒配置:', config);
            
            // 保存到场景settings
            const response = await fetch(`/api/projects/${currentProject.id}/scenes/${sceneId}/settings`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    skybox: config
                })
            });
            
            const result = await response.json();
            if (!result.success) {
                throw new Error(result.error || '保存失败');
            }
            
            // 保存成功
            this.savedConfig = config;
            this.markAsSaved();
            this.showSaveStatus('✅ 天空盒配置已保存到场景', 'success');
            console.log('✅ 天空盒配置保存成功');
            
        } catch (error) {
            console.error('❌ 保存天空盒配置失败:', error);
            this.showSaveStatus(`❌ 保存失败: ${error.message}`, 'error');
        }
    }
    
    /**
     * 加载保存的天空盒配置
     */
    async loadSavedConfig(sceneConfig) {
        if (sceneConfig?.settings?.skybox) {
            console.log('🌌 加载保存的天空盒配置:', sceneConfig.settings.skybox);
            this.skyboxManager.applyConfig(sceneConfig.settings.skybox);
            this.events.updateUIFromConfig(sceneConfig.settings.skybox);
            this.savedConfig = sceneConfig.settings.skybox;
            this.markAsSaved();
            this.showSaveStatus('✅ 已加载保存的天空盒配置', 'success');
        }
    }
    
    /**
     * 检查是否有未保存的更改
     */
    checkUnsavedChanges() {
        return this.hasUnsavedChanges;
    }
    
    /**
     * 提示用户保存或放弃更改
     */
    async promptSaveChanges() {
        if (!this.hasUnsavedChanges) {
            return true;
        }
        
        return new Promise((resolve) => {
            if (confirm('天空盒有未保存的更改，是否保存？\n\n点击"确定"保存更改\n点击"取消"放弃更改')) {
                this.saveSkyboxConfig().then(() => {
                    resolve(true);
                }).catch(() => {
                    resolve(false);
                });
            } else {
                this.hasUnsavedChanges = false;
                resolve(true);
            }
        });
    }
    
    /**
     * 销毁面板
     */
    dispose() {
        if (this.panel) {
            this.panel.remove();
            this.panel = null;
        }
        
        const style = document.getElementById('skybox-panel-styles');
        if (style) {
            style.remove();
        }
        
        // 移除工具栏按钮
        const skyboxBtn = document.querySelector('[data-tab="skybox"]');
        if (skyboxBtn) {
            skyboxBtn.remove();
        }
    }
}

export default SkyboxPanel;
